package com.morpheus.sms;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class Main extends Activity {

	private LocationManager locationManager;
	private Location currentLocation;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Button b = (Button) findViewById(R.id.button1);
		b.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				handleReverseGeocodeClick();

			}

		});

		// Get an instance of the android system LocationManager
		// so we can access the phone's GPS receiver
		this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		// Subscribe to the location manager's updates on the current location
		this.locationManager.requestLocationUpdates("gps", (long) 30000,
				(float) 10.0, new LocationListener() {
					public void onLocationChanged(Location arg0) {
						handleLocationChanged(arg0);
					}

					public void onProviderDisabled(String arg0) {
						// TODO Auto-generated method stub

					}

					public void onProviderEnabled(String arg0) {
						// TODO Auto-generated method stub

					}

					public void onStatusChanged(String arg0, int arg1,
							Bundle arg2) {
						// TODO Auto-generated method stub
					}
				});
	}

	private void handleLocationChanged(Location loc) {
		// Save the latest location
		this.currentLocation = loc;
	}

	private void handleReverseGeocodeClick() {
		if (this.currentLocation != null) {
			// Kickoff an asynchronous task to fire the reverse geocoding
			// request off to google
			ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask();
			task.applicationContext = this;
			task.execute();
		} else {
			// If we don't know our location yet, we can't do reverse
			// geocoding - display a please wait message
			showToast("Please wait until we have a location fix from the gps");
		}
	}

	public void showToast(CharSequence message) {
		int duration = Toast.LENGTH_SHORT;

		Toast toast = Toast
				.makeText(getApplicationContext(), message, duration);
		toast.show();
	}

	public class ReverseGeocodeLookupTask extends AsyncTask<Void, Void, String> {
		protected Context applicationContext;

		@Override
		protected void onPreExecute() {
			ProgressDialog.show(applicationContext, "Please wait...",
					"Searching for current location", true);
		}

		@Override
		protected String doInBackground(Void... params) {
			String Address = "";

			if (currentLocation != null) {
				Address = Geocoder.reverseGeocode(currentLocation);
			}
			return Address;
		}

		@Override
		protected void onPostExecute(String result) {

			if (result.toLowerCase().contains("singapore")) {

				String[] splits = result.split("\\s");
				int number = splits.length;

				if (splits[number-1].equalsIgnoreCase("singapore")) {

					AlertDialog.Builder builder = new AlertDialog.Builder(
							Main.this);
					builder.setMessage(
							"Your location does not have a postal code.")
							.setCancelable(false)
							.setPositiveButton("Ok, i'm out of here",
									new DialogInterface.OnClickListener() {

										public void onClick(
												DialogInterface dialog, int id) {
											// goes to second activity
											Intent nextactivity = new Intent(
													Main.this, Main.class);
											nextactivity
													.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
											startActivity(nextactivity);
										}
									})
							.setNegativeButton("Let me choose my location",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											// goes to GooglemapsActivity and
											// return
											// location changed
											Intent nextactivity = new Intent(
													Main.this,
													GooglemapsActivity.class);
											nextactivity
													.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
											startActivity(nextactivity);
										}
									});
					builder.create();
					builder.show();
				} else {

					// result to distill postal code
					String[] result_array = result.split("Singapore");
					final String postal_code = result_array[1];

					// Alert Dialog to confirm booking location
					AlertDialog.Builder builder = new AlertDialog.Builder(
							Main.this);

					// to be able to display booking location
					builder.setMessage("Your Booking Location is " + result)

							.setCancelable(false)
							.setPositiveButton("Confirm",
									new DialogInterface.OnClickListener() {

										public void onClick(
												DialogInterface dialog, int id) {
											// goes to second activity
											Intent nextactivity = new Intent(
													Main.this, Second.class);
											nextactivity
													.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
											startActivity(nextactivity);

											// book the cab
											String cab = "98890278";
											String book = "Book " + postal_code
													+ " #Pick-up point";
											sendSMS(cab, book);
										}
									})
							.setNeutralButton("Change",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											// goes to GooglemapsActivity
											// and return
											// location changed
											Intent nextactivity = new Intent(
													Main.this,
													GooglemapsActivity.class);
											nextactivity
													.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
											startActivity(nextactivity);
										}
									})
							.setNegativeButton("Cancel",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											// goes back to main activity
											Intent nextactivity = new Intent(
													Main.this, Main.class);
											nextactivity
													.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
											startActivity(nextactivity);
										}
									});
					builder.create();
					builder.show();
				}
			} else {
				AlertDialog.Builder builder = new AlertDialog.Builder(Main.this);
				builder.setMessage("You are not in Singapore.")
						.setCancelable(false)
						.setPositiveButton("Ok, i'm out of here",
								new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog,
											int id) {
										// goes to second activity
										Intent nextactivity = new Intent(
												Main.this, Main.class);
										nextactivity
												.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
										startActivity(nextactivity);
									}
								})
						.setNegativeButton("Nope, I trust myself",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										// goes to GooglemapsActivity
										// and return
										// location changed
										Intent nextactivity = new Intent(
												Main.this,
												GooglemapsActivity.class);
										nextactivity
												.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
										startActivity(nextactivity);
									}
								});
				builder.create();
				builder.show();
			}

		}

	}

	// sends sms
	protected void sendSMS(String cab, String book) {
		PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,
				SmsReceiver.class), 0);
		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(cab, null, book, pi, null);
	}
}
